<template>
  <div style="width: 100%">
    <el-input type="textarea" style="width: 100%" :placeholder="placeholder"
              :value="showText" readonly @click="openModal"/>

    <FModal header="副岗" ref="refFModal" @ok="ok">
      <FPage>
        <template #header>
          <div style="padding: 5px">
            <el-button icon="add" round type="primary" @click="addNew">添加</el-button>
          </div>
        </template>

        <div class="user-vice-page-body">
          <div v-for="(item, index) in editingList" class="user-vice-item">
            <div class="user-vice">
              <el-text truncated class="user-vice-item-label">
                部门
              </el-text>
              <el-tree-select
                  v-model="item.unitId"
                  :data="unitTrees" default-expand-all
                  check-strictly node-key="id"
                  :props="defaultProps" style="flex: 0.5"
                  :render-after-expand="false"
                  @change="() => unitChange(item)"
              />

              <el-text truncated class="user-vice-item-label">
                岗位
              </el-text>

              <el-select style="flex: 0.5" v-model="item.positionId" @change="() => positionChange(item)">
                <el-option v-for="item in positionOptions" :key="item.id"
                           :label="item.positionName" :value="item.id"/>
              </el-select>

              <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  title="确定删除吗?"
                  @confirm.stop="() => removeVice(item)">
                <template #reference>
                  <el-button style="margin-left: 10px" circle size="small" icon="remove"/>
                </template>
              </el-popconfirm>
            </div>
            <el-divider class="user-vice-divider"
                        v-show="index < editingList.length - 1"/>
          </div>
        </div>
      </FPage>
    </FModal>
  </div>
</template>
<script setup>
import FModal from '@/components/FModal/index.vue';
import {computed, nextTick, reactive, ref, shallowRef} from 'vue';
import {findListTitle, isEmpty, listToTrees, real, treesForeach} from '@/utils/CommonUtils';
import FPage from '@/components/layout/FPage.vue';
import {getAction} from '@/request/BaseRequest';
import {ElMessage} from 'element-plus';

// [
//   {positionId: '', positionName: '', unitId: '', unitName: ''}
// ]
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => {
      return reactive([]);
    },
  },
  unitData: {
    type: Object,
    default: () => ({})
  },
  placeholder: undefined,
});
const defaultProps = {
  children: 'children',
  label: 'unitName',
};
const emits = defineEmits(['update:modelValue']);
const refFModal = shallowRef();
const editingList = ref([]);
const unitTrees = ref([]);
const positionOptions = ref([]);
const loading = ref(false);

function openModal() {
  refFModal.value.open();
  editingList.value = JSON.parse(JSON.stringify(real(props.modelValue)));
  loadUnitsByPath();
  loadUnitPositions();
}

function loadUnitPositions() {
  loading.value = true;
  getAction('/sys/position/loadUnitPosition',
      {unitId: props.unitData.id, current: 1, size: 1000}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      positionOptions.value = result.records;
    }
  });
}


function loadUnitsByPath() {
  loading.value = true;
  getAction('/sys/unit/loadDepatrsByPath',
      {path: props.unitData.path}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      setUnitTrees(result);
    }
  });
}

function setUnitTrees(list) {
  let trees = listToTrees(list);
  if (isEmpty(trees)) {
    trees = [];
  }
  trees.forEach(item => {
    item.disabled = true;
  });
  unitTrees.value = trees;
}

function addNew() {
  editingList.value.push(createDefaultValue());
}

function createDefaultValue() {
  return {
    positionId: undefined,
    positionName: undefined,
    unitId: undefined,
    unitName: undefined
  };
}

const showText = computed(() => {
  let list = props.modelValue;
  if (isEmpty(list)) list = [];
  list = list.map(item => `${item.unitName}: ${item.positionName}`);
  return list.toString();
});

function removeVice(item) {
  let index = editingList.value.findIndex(i => i === item);
  if (index !== -1) {
    editingList.value.splice(index, 1);
  }
  let list = [...editingList.value];
  editingList.value = [];
  nextTick(() => {
    editingList.value = list;
  });
}

function ok() {
  let list = real(editingList);
  if (isEmpty(list)) {
    list = [];
  }
  for (let i = 0; i < list.length; i++) {
    let item = list[i];

    if (isEmpty(item.unitId) || isEmpty(item.positionId)) {
      ElMessage({
        message: '请填写必填项',
        type: 'warning',
      });
    }
  }
  list = real(editingList);
  let listTemp = [];
  list.forEach(item => {
    let temp = listTemp.find(i => i.unitId === item.unitId
        && i.positionId === item.positionId);
    if (isEmpty(temp)) {
      listTemp.push(real(item));
    }
  });
  emits('update:modelValue', listTemp);
  refFModal.value.close();
}

function unitChange(item) {
  treesForeach(real(unitTrees), node => {
    if (item.unitId === node.id) {
      item.unitName = node.unitName;
    }
  });
}

function positionChange(item) {
  item.positionName = findListTitle(item.positionId, real(positionOptions), 'positionName');
}

</script>
<script>
export default {
  name: 'VicePositionModal'
};
</script>
<style>
.user-vice-divider {
  margin: 0;
  background: white;
}

.user-vice-item {
  background: white;
}

.user-vice {
  padding: 10px 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-width: 0 2px 0 2px;
  border-color: #f0f2f5;
  border-style: solid;
}

.user-vice-item-label {
  width: 60px;
  text-align: right;
  padding-right: 10px;
}

.user-vice-page-body {
}

.f-modal-fullscreen-body .user-vice-page-body {
  height: 100%;
}

.f-page-body .user-vice-page-body {
  height: 500px;
}
</style>
